package com.we823.project.common.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;

public class ReadExcelUtil {
	public HSSFWorkbook readExcel(File file) {
		POIFSFileSystem poifsFileSystem = null;
		HSSFWorkbook hssfWorkbook = null;
		FileInputStream stream = null;
		
		try {
			stream = new FileInputStream(file);
			poifsFileSystem = new POIFSFileSystem(stream);
			hssfWorkbook = new HSSFWorkbook(poifsFileSystem);
		}catch(Exception ex) {
			if (poifsFileSystem==null) {
			}
		}finally {
			try {
				stream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return hssfWorkbook;
	}
	
	/**
	 * 计算是否为空行
	 * @param row
	 * @param index
	 * @return
	 */
	public boolean checkRowBlank(HSSFRow row, int index) {
		int cellCount = row.getPhysicalNumberOfCells();
		int blankCount = 0;
		for (int cellIndex = 0; cellIndex < cellCount; cellIndex++) {
			HSSFCell cell = row.getCell(cellIndex);
			int cellType = cell.getCellType();
			if (Cell.CELL_TYPE_BLANK == cellType) {
				blankCount++;
			}
		}
		boolean isBlank = (blankCount == cellCount) ? true : false;
		return isBlank;
	}
	
	/**
	 * 按照字符串取出纯数字内容，同时保留小数点
	 * @param structureCell
	 * @return
	 */
	public String parseNumericCellToString(HSSFCell cell) {
		if (cell!=null) {
			if (Cell.CELL_TYPE_NUMERIC==cell.getCellType()) {
				double dValue = cell.getNumericCellValue();
				return String.valueOf(dValue);
			}
			
			cell.setCellType(Cell.CELL_TYPE_STRING);
			return cell.getStringCellValue();
		}
		return "";
	}
	
}
